package org.jeecg.modules.vinQuery.service;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class VinQueryService {

    private WebDriverManager webDriverManager;

    @Autowired
    public VinQueryService(WebDriverManager webDriverManager) {
        this.webDriverManager = webDriverManager;
    }

    @Async
    public String startQueryAndGetCaptcha(String openId) throws InterruptedException, IOException {
        WebDriver driver = webDriverManager.createDriver(openId);
        driver.get("https://info.vecc.org.cn/ve/vin/index");


        // 等待验证码加载
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement captchaElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("vaild")));

        // 保存验证码图片
        String captchaImgPath = saveCaptchaImage(driver, captchaElement);

        return captchaImgPath;
    }

    @Async
    public Map<String, String> submitCaptchaAndFetchResult(String openId, String vin, String engine, String captcha) throws Exception {
        WebDriver driver = webDriverManager.getDriver(openId);
        if (driver == null) {
            throw new IllegalStateException("Session not found or WebDriver instance has been closed.");
        }
        Map<String, String> result = new HashMap<String, String>();

        driver.findElement(By.name("vin")).clear();
        driver.findElement(By.name("fdjh")).clear();
        driver.findElement(By.name("vaild")).clear();
        driver.findElement(By.name("vin")).sendKeys(vin);
        driver.findElement(By.name("fdjh")).sendKeys(engine.substring(engine.length() - 6));
        driver.findElement(By.name("vaild")).sendKeys(captcha);
        driver.findElement(By.cssSelector("img[src='../images/query.jpg']")).click();

        // 检查是否有弹窗提示
        if (isAlertPresent(driver)) {
            String alertText = getAlertText(driver);
            result.put("error", alertText);
        } else {
            String currentUrl = driver.getCurrentUrl();
            Document doc = Jsoup.connect(currentUrl).get();
            Elements elements = doc.select("[class*=MsoNormal]");
            if (elements.isEmpty()){
                return result;
            }
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                String content = element.text();
                if (content.contains(" 车辆型号")) {
                    result.put("carModel", elements.get(i+1).text());
                }
                if (content.contains(" 商 标") || content.contains(" 商标")) {
                    result.put("carBrand", elements.get(i+1).text());
                }
                if (content.contains(" 排放阶段") && i + 1 < elements.size()) { // 确保不会超出索引范围
                    String text = elements.get(i + 1).text();
                    // 定义匹配“国五”的正则表达式，确保完整匹配“国五”的各种形式，并排除“国VI”
                    Pattern patternFive = Pattern.compile("(国\\s*五|国\\s*5|国\\s*５|国\\s*[Vv](?!I|i))", Pattern.CASE_INSENSITIVE);
                    Matcher matcherFive = patternFive.matcher(text);
                    // 定义匹配“国六”的正则表达式，确保完整匹配“国六”的各种形式
                    Pattern patternSix = Pattern.compile("(国\\s*六|国\\s*6|国\\s*６|国\\s*(VI|vi))", Pattern.CASE_INSENSITIVE);
                    Matcher matcherSix = patternSix.matcher(text);
                    if (matcherSix.find()) {
                        result.put("evnType", "6"); // 如果匹配到任何形式的“国六”
                    } else if (matcherFive.find()) {
                        result.put("evnType", "5"); // 如果匹配到任何形式的“国五”
                    }
                    result.put("evnType_dictText", text);
                }
                if (content.contains(" 发动机型号")) {
                    String text = elements.get(i + 1).text();
                    if (text.contains("/")){
                        String[] split = text.split("/");
                        result.put("engineType", split[0]);
                        result.put("engineManufacturer", split[1]);
                    } else {
                        result.put("engineType", text);
                    }
                }
                if (content.contains(" 电动机型号")) {
                    String text = elements.get(i + 1).text();
                    if (text.contains("/")){
                        String[] split = text.split("/");
                        result.put("engineType", split[0]);
                        result.put("engineManufacturer", split[1]);
                    } else {
                        result.put("engineType", text);
                    }
                }
                if (content.contains(" 制造商名称")) {
                    result.put("engineManufacturer", elements.get(i+1).text());
                }
            }
        }
        return result;
    }

    public String refreshCaptcha(String openId) throws InterruptedException, IOException {
        WebDriver driver = webDriverManager.getDriver(openId);
        if (driver == null) {
            throw new IllegalStateException("遇到了错误, 请退出页面重新进入。");
        }

        // 假设点击这个元素可以刷新验证码
        WebElement captchaElement = driver.findElement(By.id("vaild"));
        captchaElement.click();
        Thread.sleep(1000); // 等待一段时间以确保验证码已更新

        // 保存新的验证码图片
        return saveCaptchaImage(driver, captchaElement);
    }

    public void cleanupResources(String openId) {
        webDriverManager.removeDriver(openId);
    }

    private boolean isAlertPresent(WebDriver driver) {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String getAlertText(WebDriver driver) {
        Alert alert = driver.switchTo().alert();
        String text = alert.getText();
        alert.accept();
        return text;
    }

    private String saveCaptchaImage(WebDriver driver, WebElement captchaElement) throws IOException {
        // 定义图片存放路径包括文件名，使用UUID生成唯一的文件名以避免冲突
        String fileName = UUID.randomUUID() + ".png";
        String filePath = "C:/tw_env_pro/tempImg/" + fileName; // 替换为实际的文件存储路径
        File screenshot = captchaElement.getScreenshotAs(OutputType.FILE);

        // 将临时截图移动到指定位置保存
        File targetFile = new File(filePath);
        FileUtils.copyFile(screenshot, targetFile);

        // 返回相对路径或URL供前端访问
        return fileName; // 根据实际情况调整返回路径
    }

}